<template>
  <div class="head">

    <div style="width: 60%;">
      <ul class="index">
        <li :class="{ 'dynamic': navbarIndex == idx, 'static': true }" v-for="(item, idx) in pagesTitle"
            :key="item.sort"
            @click="changePages(item.path, idx)">{{ item.title }}
        </li>
      </ul>
    </div>

    <div style="display: flex;width: 30%;line-height:60px;">
      <div>
        <el-input v-model="input" style="width: 220px" placeholder="请输入搜索内容" clearable/>
      </div>
      <div @click="search()">
        <el-button :icon="Search" circle type="primary" size="default" style="margin-left: 10px;"/>
      </div>
    </div>

    <div class="all " title="个人信息" style="display: flex;width: 10%;line-height: 60px;"
         @click="drawer = true">
      <div>
        <el-avatar :size="45" :src="userInfo.picture" style="margin-top: 8.5px;"/>
      </div>
      <div style="margin-left: 15%;">
        <el-text class="mx-1" type="primary">
          {{ userInfo.name }}
        </el-text>
      </div>
    </div>
  </div>


  <el-drawer v-model="drawer" :before-close="handleClose">
    <template #header>
      <div style="color:  #79bbff;">个人信息</div>
    </template>

    <template #default>

      <div style="width: 100%;">

        <div style="height: 20%;width: 100%;text-align: center;">
          <div>
            <el-upload class="avatar-uploader"
                       method="post" action="http://localhost:8080/files/upload"
                       :show-file-list="false"
                       :headers="{'token' : userInfo.token}"
                       :on-success="        (response, file, fileList) => {
          return uploadSuccess(response);
        }">
              <img v-if="userInfo.picture" :src="userInfo.picture" class="avatar"/>
              <el-icon v-else class="avatar-uploader-icon">
                <Plus/>
              </el-icon>
            </el-upload>
          </div>
        </div>
        <el-form :model="userInfo" style="margin-top: 5%;text-align: center;">
          <el-form-item label="姓名">
            <el-input v-model="userInfo.name"/>
          </el-form-item>
          <el-form-item label="年龄">
            <el-input v-model="userInfo.age"/>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="userInfo.mailbox" disabled/>
          </el-form-item>
          <el-form-item label="身份">
            <el-input v-model="userInfo.role" disabled/>
          </el-form-item>
        </el-form>
      </div>
    </template>
    <template #footer>
      <div style="display: flex;justify-content: center;">
        <el-button type="warning" @click="passwordStatus = true">
          修改密码
        </el-button>
        <el-button type="primary" @click="changeUserInfo()">
          保存信息
        </el-button>
        <el-button type="danger" @click="logout()">
          退出登录
        </el-button>
      </div>
    </template>
  </el-drawer>

  <el-dialog
      v-model="passwordStatus"
      title="修改密码"
      width="500"
      :before-close="handleClose"
  >
    <template #default>
      <el-input v-model="passwordData" placeholder="请输入密码"/>
    </template>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="passwordStatus = false">取消</el-button>
        <el-button type="primary" @click="changePassword">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {ref, computed, onMounted, onBeforeUnmount} from 'vue'
import {Plus, Search} from '@element-plus/icons-vue'
import axios from 'axios'
import {ElMessage} from 'element-plus'
import {useUserInfoStore} from '@/stores/user'
import {useRouter,useRoute} from 'vue-router';
const useRoute1 = useRoute();
const userStore = useUserInfoStore();

// console.log("路径",useRoute1.fullPath.split("/"))


// const serverUrl = "http://localhost:8080/files/shows/;
const circleUrl = ref("http://localhost:8080/files/shows/" + userStore.images);

const drawer = ref(false)
const input = ref("");

const strings = useRoute1.fullPath.split("/");
if(strings >= 4 && strings[2] != "writes" ){
  input.value = useRoute1.fullPath.split("/")[3] == "75395123" ? ""
      : decodeURIComponent(useRoute1.fullPath.split("/")[3])
}
// const selectIndex = ref(0);
const dialogFormVisible = ref(false)
const dialogForm = ref({});

const navbarIndex = ref(0);

const passwordStatus = ref(false);
const passwordData = ref("");
const userInfo = ref({
  token: "",
  name: "",
  picture: "",
  mailbox: "",
  age: "",
})

const loginStatus = ref(true);

const pagesTitle = ref([
  {
    sort: 1,
    title: "首页",
    path: "/index/home/75395123",

  },
  {
    sort: 2,
    title: "生活",
    path: "/index/life/75395123",
  },
  // {
  //   sort: 3,
  //   title: "技术",
  //   path: "/technology",
  // },
  {
    sort: 4,
    title: "创作",
    path: "/index/write",
  },

])

const router = useRouter()
// console.log("路径",router.options.routes[0].id)

const changePages = (path, idx) => {
  router.push(path);
  navbarIndex.value = idx;
  localStorage.setItem("navbarIndex", String(navbarIndex.value));
  setTimeout(function () {
    router.go()
  },100)
  // router.go()
}

const showDialog = () => {
  dialogFormVisible.value = !dialogFormVisible.value
  if (dialogFormVisible.value == false) {
    dialogForm.value = {}
    loginStatus.value = true
  }
}

onMounted(() => {
  loginToken();
  if (localStorage.getItem("navbarIndex") != null && localStorage.getItem("navbarIndex") !== undefined) {
    navbarIndex.value = Number(localStorage.getItem("navbarIndex"))
  }
})

onBeforeUnmount(() => {
  localStorage.setItem("navbarIndex", "0")
})

const loginToken = () => {
  const token = localStorage.getItem("token");
  if (token == null || token === "") {
    ElMessage({
      message: "请先登录",
      type: 'warning',
      duration: 3000
    })

    setTimeout(function () {
      router.replace("/")
    }, 1000);

    return
  }

  axios.get("user/token").then(res => {
    console.log(res)
    const data = res.data;
    userInfo.value.mailbox = data.mailbox;
    userInfo.value.picture = "http://localhost:8080/files/shows/" + data.picture;
    userInfo.value.name = data.name;
    userInfo.value.age = data.age
    userInfo.value.token = localStorage.getItem('token');
    userInfo.value.role = res.data.role == 2 ? "普通用户" : "管理员"
  })
}

const handleClose = () => {
  drawer.value = false
}

// 搜索
const search = () => {
  // console.log("搜索的内容:", input.value)
  const name = useRoute1.name;
  console.log("路径",name)
  if (name == "life") {

    if(input.value == "" || input.value == null || input.value == undefined){
      input.value = "75395123"
    }

    setTimeout(function () {
      router.push("/index/life/" + input.value)
      // input.value = ""

    }, 500);


  }else {
    if(input.value == "" || input.value == null || input.value == undefined){
      input.value = "75395123"
    }
    setTimeout(function () {
      router.push("/index/home/" + input.value)
      // input.value = ""

    }, 500);
  }
  setTimeout(function (){router.go()},1000)
}


const changeUserInfo = () => {
  // submitUpload();
  console.log(userInfo.value)
  const newUserInfo = {
    "name" : userInfo.value.name,
    "picture" : userInfo.value.picture,
    "age" : userInfo.value.age,
  }

  axios.post("user/update", newUserInfo).then(res => {
    ElMessage({
      message: "修改成功",
      type: 'success',
      duration: 3000
    })

    setTimeout(function () {
      loginToken()
      drawer.value = false
    }, 1000)
  })
}


const uploadSuccess = (response) => {
  // console.log(response)
  userInfo.value.picture = "http://localhost:8080/files/shows/" + response.message
}

const logout = () => {
  axios.get("user/logout").then(res => {

    ElMessage({
      message: "退出成功",
      type: 'success',
      duration: 3000
    })

    localStorage.removeItem("token")
    localStorage.removeItem("navbarIndex")
    setTimeout(function () {
      router.replace("/")
    }, 1000);
  })
}

const changePassword = () => {
  axios.get("/user/password?password=" + passwordData.value).then(res => {
    ElMessage({
      message: res.message,
      type: 'success',
      duration: 2000
    })

    setTimeout(function () {
      logout()
    }, 1000)
  })
}
</script>

<style scoped>
.all {
  cursor: pointer;
}

.head {
  display: flex;
  background-color: white;
  width: 100%;
  justify-content: space-evenly;
  height: 60px;
}

.index {
  display: flex;
  justify-content: space-evenly;
  list-style-type: none;
  width: 100%;
  height: 100%;
}

.static {
  width: 7%;
  text-align: center;
  height: 100%;
  line-height: 60px;
}

.index li:hover {
  cursor: pointer;
  background-color: #79bbff;
  color: white;
}

.dynamic {
  /* width: 7%;
  text-align: center;
  height: 100%;
  line-height: 60px; */
  background-color: #79bbff;
  color: white;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
  border-radius: 50%;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>